package com.cbtx.networklib.interceptor

import com.cbtx.networklib.util.SignUtil
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 9:50 AM
 * desc   :
 */
class CommonParamsInterceptor() : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
        val builder = FormBody.Builder()
        if (request.body is FormBody) {
            // 构造新的请求表单
            val body = request.body as FormBody?
            // 将原来的参数放入新的表单中
            for (i in 0 until body!!.size) {
                builder.addEncoded(body.encodedName(i), body.encodedValue(i))
            }
        }
        // 添加公共参数
        val currentTime = System.currentTimeMillis()
        builder.addEncoded("timestamp", "" + currentTime)
        val reqBuild = request.newBuilder()
        //分辨率 not null
        reqBuild.addHeader("resolution", "1280x800")
        reqBuild.addHeader("sign", SignUtil.getSign(request, currentTime))
        request = reqBuild.post(builder.build()).build() //构造新的请求体

        return chain.proceed(request)
    }
}